package top.yueyazhui.vhr.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JwtFilter extends GenericFilterBean {

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String url = request.getRequestURI();

        System.out.println("url = " + url);

        List<String> passUrls = new ArrayList<>();

        /** swagger start **/
        passUrls.add("/swagger-ui.html");
        passUrls.add("/favicon.ico");
        passUrls.add("/webjars/**");
        passUrls.add("/swagger-resources/**");
        passUrls.add("/v2/api-docs/**");
        /** swagger end **/

        for(String passUrl : passUrls){
            if(antPathMatcher.match(passUrl, url)){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        String jwtToken = request.getHeader("authorization");
        Jws<Claims> jws = Jwts.parser().setSigningKey("yueyazhui.top")
                .parseClaimsJws(jwtToken.replace("Bearer", ""));
        Claims claims = jws.getBody();
        String username = claims.getSubject();
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(((String) claims.get("authorities")));
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
